/**
 * 通用脚本
 */
/**==================================窗口/tab开始===========================*/
/** 打开窗口
 * @param title 标题
 * @param url 路径url
 * @param width/height 窗口组件长度和高度,当值为-1时，展开为最大窗口
 * @param pid 点击关闭按钮时执行父级页面方法，方法默认定义为：reloadParent(pid),请务必保证父页面存在此方法;
 */
function openWin(title, url, width, height, pid) {
	if (!isNaN(width)) {
		if (width == -1) width = $(window).width();
		width = width + "px";
	}
    if (!isNaN(height)) {
		if (height == -1) height = $(window).height();
		height = height + "px";
	}
    //if (isNaN(closeBtn)) closeBtn = 1;// 默认设置为关闭状态
	layui.use('layer', function() {
    	var layer = layui.layer;
        var index = layer.open({
            type: 2 //此处以iframe举例
            ,title: title
            ,area: [width, height] //宽高自适应
            ,shade: 0.3
            ,maxmin: true
            //,closeBtn: closeBtn
            ,content: url
            ,end: function () {//窗口关闭后执行的方法
               if (pid != '' && pid != null && pid) reloadParent(pid);
         }
        });
     });
}
/** 在当前窗口的父级打开窗口
 * @param title 标题
 * @param url 路径url
 * @param width/height 窗口组件长度和高度,当值为-1时，展开为最大窗口
 */
function openTopWin(title, url, width, height) {
	if (!isNaN(width)) {
		if (width == -1) width = $(window).width();
		width = width + "px";
	}
    if (!isNaN(height)) {
		if (height == -1) height = $(window).height();
		height = height + "px";
	} 
	layui.use('layer', function() {
    	var layer = layui.layer;
        var index = parent.layer.open({
            type: 2 //此处以iframe举例
            ,title: title
            ,area: [width, height] //宽高自适应
            ,shade: 0.3
            ,maxmin: true
            ,content: url
            /* ,end: function () {//窗口关闭后执行的方法
               if (reload != '' && reload != null && reload) location.reload();
               if (dataGrid != '' && dataGrid != null) $('#' + dataGrid).trigger('reloadGrid');
         } */
        });
     });
}

function closeWin() {// 关闭窗口
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

/** 打开页签
 * @param title 标题
 * @param url 路径url
 */
function openTab(title, url) {
	var id = Math.random().toString(36).substr(2);//默认赋予一个id
    top.$.addtabs.add({'id': id, 'url': url, 'title': title});
}
function closeTab() {// 关闭页签
	/*window.parent.$.addtabs.closeself(); */
    top.$.addtabs.closeself();
}
/**==================================窗口/tab结束===========================*/

/**==================================表Jqgrid格操作开始===========================
function customJQGridSearch(ele,jqgridId){
    var form = $(ele).closest("form");
    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    var postData = $("#"+jqgridId).jqGrid("getGridParam", "postData");
    // (5)将查询参数融入postData选项对象
    $.extend(postData, {params:o});
    $("#"+jqgridId).jqGrid("setGridParam", {
        search: true
    }).trigger("reloadGrid",[{page:1}]);
}
function customJQGridSearchReset(ele,jqgridId){
    var postData = $("#"+jqgridId).jqGrid("getGridParam", "postData");
    var form = $(ele).closest("form");
    $.extend(postData, {params:{}});
    $("#"+jqgridId).jqGrid("setGridParam", {
        search: true
    }).trigger("reloadGrid", [{page:1}]);
    $(form)[0].reset();
}
 */
/**
 * jqgrid查询
 * @param grid

$.fn.customJQGridSearch=function(grid){
    var o = $(this).formToJson();
    var postData = $("#"+grid).jqGrid("getGridParam", "postData");
    // (5)将查询参数融入postData选项对象
    $.extend(postData, {params:o});
    $("#"+grid).jqGrid("setGridParam", {
        search: true
    }).trigger("reloadGrid", [{page:1}]);
}
 */
/**
 * 清除查询条件
 * @param grid

$.fn.customJQGridSearchReset=function(grid){
    var postData = $("#"+grid).jqGrid("getGridParam", "postData");
    $.extend(postData, {params:{}});
    $("#"+grid).jqGrid("setGridParam", {
        search: true
    }).trigger("reloadGrid", [{page:1}]);
    $(this)[0].reset();
}
 */
/** Jqgrid表头添加标题
$.fn.addTopBtns = function(config){
    var button = {label:'newButton',icon:'icon-default',handler:null,id:null};
    var selector = this.selector;
    var topSelector = null;
    if(selector){
         topSelector = "#t_"+selector.substring(1,selector.length);
    }
    if(config!=null&&config.length>0&&topSelector){
        $(this).jqGrid("setGridParam",{toolbar:[true,'top']});
        var bar = $(topSelector);
        $(config).each(function(){
            //判断是否为空按钮
            if(this.label==null&&this.icon==null){
                return;
            }
            var btnConfig = $.extend(true,{},button,this);
            var icon = $("<i/>").addClass(btnConfig.icon);
            var btn = $("<button type='button'/>").attr("id",btnConfig.id).append(icon).addClass("btn btn-small").append("  "+btnConfig.label).click(function(){
                if($(selector).getGridParam("multiselect")){
                    btnConfig.handler($(selector).selMultipleRow(),$(selector),this);
                }else{
                    btnConfig.handler($(selector).selRow(),$(selector),this);
                }
            }).appendTo(bar);
        })
    }
}
$.fn.disableTopBtns=function() {
    var selector = this.selector;
    var topSelector = null;
    if(selector){
        topSelector = "#t_"+selector.substring(1,selector.length);
    }
    if(topSelector){
        $(topSelector).find("button").each(function(){
            $(this).attr("disabled","disabled");
        })
    }
}
$.fn.enableTopBtns=function() {
    var selector = this.selector;
    var topSelector = null;
    if(selector){
        topSelector = "#t_"+selector.substring(1,selector.length);
    }
    if(topSelector){
        $(topSelector).find("button").each(function(){
            $(this).removeAttr("disabled");
        })
    }
}
 */
/**==================================表格操作结束===========================*/

/**==================================Json序列化开始===========================
function formToJson(form){
    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
 */
/**
 * form转换为json对象
 * @returns {{}}

$.fn.formToJson = function() {
    var o = {};
    var a = $(this).serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}
 */
/**==================================soultable相关函数开始===========================*/
/**
 *
 * @param data 搜索栏字段，根据ID定义
 * @param soulTable 对象
 * @param url 表格重新加载的url
 */
function search(data, soulTable, url) {
	var field = data.field;
	var flag = true;
	for(var attr in field) {
		var v = field[attr];
		if (v != '') {
			flag = false;
    		break;
		}
	}
    if (flag) {
    	layer.msg("请输入查询条件", {icon: 2});
    } else {
        soulTable.reload({  // 重载 table
			url : url,
            where: field,
            contentType: 'application/json'
        	,page: {curr : 1}
        });
		table_resize(soulTable.config.id);
    }
}
/**
 * myTable soultable ID
 * 查询区域元素收缩与展开
 */
function more_click(myTable) {//查询元素太多，隐藏
	if ($(".more-container").is(":hidden")) {
      $(".more-container").show(); //如果元素为隐藏,则将它显现
      $(".more-btn").html('<i class="layui-icon layui-icon-subtraction"></i>收起');
    } else {
      $(".more-container").hide(); //如果元素为显现,则将其隐藏
      $(".more-btn").html('<i class="layui-icon layui-icon-addition"></i>展开');
    }
    table_resize(myTable);
    return false;
}
/** 重新刷新表格高度 */
function table_resize(tid) {
    var height_total = $(document).height();//总高度
	//console.log('------------height_total= ' + height_total);
    var height_offset = $('#' + tid).offset().top;//总高度
	//console.log('------------height_offset= ' + height_offset);
	var height_search = $('.layui-card-body').height();//搜索栏高度
	if (height_search == null) height_search = 0;
	//console.log('------------layui-card-body_search= ' + height_search);
	var height_tool = $('.layui-table-tool').height();//工具栏
	if (height_tool == null) height_tool = 0;
	//console.log('------------layui-table-tool= ' + height_tool);
	var height_page = $('.layui-table-page').height();//分页栏
	if (height_page == null) height_page = 0;
	//console.log('------------layui-table-page= ' + height_page);
	var height = height_total - height_offset - height_search - height_tool - height_page
	//console.log('------------height= ' + height);
    $(".layui-table-box").css({height: height});
}
/*选中checkbox后添加背景颜色*/
function selectRow(myTable, obj) {
    //全选时
    if (obj.type == "all") {
        if (obj.checked) {//全选中
            var checkStatus = layui.table.checkStatus(myTable);
            var sdata = checkStatus.data;
            if (sdata.length > 0) {//渲染背景颜色
                $(".layui-table-body .layui-table tr").each(function () {
                    $(this).addClass("selectRow");
                })
            }
        } else {//全部不选
            $(".layui-table-body .layui-table tr").each(function () {
                $(this).removeClass("selectRow");
            })
        }
    } else {//单选
        var checkStatus = layui.table.checkStatus(myTable);
        var sdata = checkStatus.data;
        if (obj.checked) {//选中
            obj.tr.addClass('selectRow');
        } else {//取消选中
            obj.tr.removeClass('selectRow');
        }
    }
}
/**
 * 生成指定位数的随机数
 * @param len
 * @returns {string}
 */
function randomStr(len) {//生成制定位数的随机数
    var s = '';
    var randomchar = function() {
        var n = Math.floor(Math.random()*62);
        if(n < 10) return n; //1-10
        if(n < 36) return String.fromCharCode( n + 55); //A-Z
        return String.fromCharCode(n + 61); //a-z
    }
    while(s.length < len) s += randomchar();
    return s;
}
/*
$(document).ready(function() {
    //所有下拉框使用select2
    try{
        $(".eap-select").select2();
    } catch (e) {

    }
});
 */